from flask import Flask, request
from todomanager_mysql import Todomanage_mysql
from time import sleep

app = Flask(__name__)
app.config['JSON_AS_ASCII'] = False

# sleep(5)
sql = Todomanage_mysql()
sql.get_connection()


@app.route('/')
def hello_word():
    return '<h1>hello world</h1>'


@app.route('/todos')
def get_todo():
    return {'todo': [x.__dict__ for x in sql.get_list()]}


@app.route('/create_todo', methods=['POST'])
def created():
    if 'title' not in request.json:
        return '参数错误，必须提供title参数', 400
    todo = sql.create(request.json['title'])
    return todo.__dict__


@app.route('/mark_completed', methods=['GET'])
def mark_completed():
    if 'todo_id' not in request.args:
        return '参数错误，必须提供id参数', 400
    data = sql.mark_completed(int(request.args['todo_id']))
    return data.__dict__


@app.route('/delete', methods=['GET'])
def delete():
        if 'todo_id' not in request.args:
            return '参数错误，必须提供title参数', 400
        todo = sql.delete(int(request.args['todo_id']))
        return todo.__dict__

if __name__ == '__main__':
    app.run()
